#!/usr/bin/perl

use strict;
use warnings;

our %Commands;

our $LastCommandType;    #

our @LastResult;

our $LastErrorcode;

our %ParameterRegExpValues;

our %Settings;

# show session
# show processis
# show scratches
# kill
# reach
# show disks
# show timing
# show drives

# show path
# on off

# show status
# show libvolumes
# show assoc
# delete assoc

#################
# Show SESsions ########################################################################################################
#################
&msg( '0110D', 'SHow SESsions' );
$Commands{&commandRegexp( "show", "sessions" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "show sessions Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    my @query = &runTabdelDsmadmc( "select SESSION_ID,STATE,WAIT_SECONDS,BYTES_SENT,BYTES_RECEIVED,SESSION_TYPE,CLIENT_PLATFORM,CLIENT_NAME,INPUT_VOL_ACCESS,OUTPUT_VOL_ACCESS from sessions","select_x_from_sessions" );
    #,OWNER_NAME,MOUNT_POINT_WAIT,INPUT_MOUNT_WAIT,INPUT_VOL_WAIT,INPUT_VOL_ACCESS,OUTPUT_MOUNT_WAIT,OUTPUT_VOL_WAIT,OUTPUT_VOL_ACCESS,LAST_VERB,VERB_STATE
    return 0 if ( $#query < 0 || $LastErrorcode );

    $LastCommandType = "SESSION";

    my @printable;

    foreach ( @query ) {
        my @line = split ( /\t/ );
        $line[2] = &timeFormatter ( $line[2], 's' );
        $line[3] = &byteFormatter ( $line[3], 'B' );
        $line[4] = &byteFormatter ( $line[4], 'B' );

        $line[8] = "" if ( ! defined ( $line[8] ) );
        $line[9] = "" if ( ! defined ( $line[9] ) );

        push ( @printable, join( "\t", $line[0], $line[1], $line[2], $line[3], $line[4], $line[5], $line[6], $line[7], $line[8].$line[9] ) )
    }

    &setSimpleTXTOutput();
    &universalTextPrinter( "#\tId\tState\tWait\tSent{RIGHT}\tReceived{RIGHT}\tType\tPlatform\tName\tMediaAccess", &addLineNumbers( @printable ) );
    #\tOWNER_NAME\tMOUNT_POINT_WAIT\tINPUT_MOUNT_WAIT\tINPUT_VOL_WAIT\tINPUT_VOL_ACCESS\tOUTPUT_MOUNT_WAIT\tOUTPUT_VOL_WAIT\tOUTPUT_VOL_ACCESS\tLAST_VERB\tVERB_STATE

    return 0;

};
&defineAlias( 'ls',   'show session' );
&defineAlias( 'ps',   'show session' );
&defineAlias( 'ses',  'show session' );
&defineAlias( 'sess', 'show session' );

#################
# SHow PROcesses ########################################################################################################
#################
&msg( '0110D', 'SHow PROcesses' );
$Commands{&commandRegexp( "show", "processes" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "SHow PROcesses Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    my @query = &runTabdelDsmadmc( "select PROCESS_NUM,PROCESS,STATUS from processes","select_x_from_processes" );
    #,OWNER_NAME,MOUNT_POINT_WAIT,INPUT_MOUNT_WAIT,INPUT_VOL_WAIT,INPUT_VOL_ACCESS,OUTPUT_MOUNT_WAIT,OUTPUT_VOL_WAIT,OUTPUT_VOL_ACCESS,LAST_VERB,VERB_STATE
    return 0 if ( $#query < 0 || $LastErrorcode );

    $LastCommandType = "PROCESS";

    &setSimpleTXTOutput();
    &universalTextPrinter( "#\tProc#\tProcess\tStatus", &addLineNumbers( @query ) );
    #\tOWNER_NAME\tMOUNT_POINT_WAIT\tINPUT_MOUNT_WAIT\tINPUT_VOL_WAIT\tINPUT_VOL_ACCESS\tOUTPUT_MOUNT_WAIT\tOUTPUT_VOL_WAIT\tOUTPUT_VOL_ACCESS\tLAST_VERB\tVERB_STATE

    return 0;

};
&defineAlias( 'q proc', 'show processes' );
&defineAlias( 'proc', 'show processes' );

##################
# Show SCRatches #######################################################################################################
##################
&msg( '0110D', 'SHow SCRatches' );
$Commands{&commandRegexp( "show", "scratches" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "SHow SCRatches Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    my @query = &runTabdelDsmadmc( "select LIBRARY_NAME, count(*) from libvolumes where upper(status)='SCRATCH' group by LIBRARY_NAME", "select_lib_scratches_from_libvolumes" );
    return 0 if ( $#query < 0 || $LastErrorcode );

    $LastCommandType = 'GENERAL';

    if ( $ParameterRegExpValues{HISTORY} ) {

        my @archive = &initArchiveRetriever ( 'select_lib_scratches_from_libvolumes' );
        return 0 if ( $#archive < 0 );

        while ( 1 ) {

            &setSimpleTXTOutput();
            &universalTextPrinter( "LibraryName\t#Scratch", @archive );

            @archive = &archiveRetriever();
            last if ( $#archive < 0 );

        }

    }
    else {

        &setSimpleTXTOutput();
        &universalTextPrinter( "LibraryName\t#Scratch", @query );

    }

    return 0;

};
&defineAlias( 'scr', 'show scratches' );

########
# KIll #######################################################################################################
########
&msg( '0110D', 'KILl' );
$Commands{&commandRegexp( "kill", "" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "KILl Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    my $number = $2;

    if ( $number eq '' ) {
        &msg ( '0030E' );  # missing
        return 0;
    }

    if ( defined( $LastCommandType ) && $LastCommandType =~ m/SESSION|PROCESS/ ) {

        if ( $number =~ m/\d+/ ) {

            $number--;

            if (  $number <= $#LastResult ) {

                my ( $num, $session ) = split ( /\t/, $LastResult[$number] );

                #&msg ( '0030I' );
                &universalTextPrinter( "NOHEADER", &runDsmadmc( "cancel $LastCommandType $session" ) );

            }
            else {

                &msg ( '0032E' ); # out of range

            }

        }
        elsif ( uc( $number ) eq 'ALL' ) {

            foreach ( @LastResult ) {
                my ( $num, $session ) = split ( /\t/, $_ );
                &universalTextPrinter( "NOHEADER", &runDsmadmc( "cancel $LastCommandType $session" ) );
            }

        }
        else {
          #wrong parameter

        }
    }
    else {

        &msg ( '0031E', "Only 'SHow Sessions' OR 'SHow PROcesses' allowed" );

    }

    return 0;

};

########
# REAch #######################################################################################################
########
&msg( '0110D', 'REAch' );
$Commands{&commandRegexp( "reach", "" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "REAch Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    my $number = $2;

    if ( $number eq '' ) {
        &msg ( '0030E' );
        return 0;
    }

    $number--;

    if ( defined( $LastCommandType ) && $LastCommandType =~ m/SESSION/ && $number <= $#LastResult ) {

        my ( $num, $session, $state, $wait, $sent, $received, $type, $platform, $node_name ) = split ( /\t/, $LastResult[$number] );

        my @url = &runTabdelDsmadmc( "select URL from NODES where NODE_NAME='".$node_name."'" );

        if ( ! defined ( $url[0] ) || $url[0] eq '' ) {

            &msg ( '0050E', $node_name );

        }
        else {

            &reach ( $url[0] );

        }

    }
    elsif ( $number > $#LastResult ) {

        &msg ( '0032E' ); # out of range

    }
    else {

        &msg ( '0031E', "Only 'SHow Sessions' allowed" );

    }

    return 0;

};

##############
# Show DISks ###########################################################################################################
##############
&msg( '0110D', 'SHow DISks' );
$Commands{&commandRegexp( "show", "disks" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "SHow DISks Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    my @query = &runTabdelDsmadmc( "select STGPOOL_NAME,EST_CAPACITY_MB,PCT_UTILIZED,PCT_MIGR,HIGHMIG,LOWMIG,NEXTSTGPOOL from STGPOOLS where DEVCLASS='DISK'", 'select_x_from_stgpools' );
    return if ( $#query < 0 || $LastErrorcode );

    $LastCommandType = 'GENERAL';

    my @printable;

    foreach ( @query ) {
      my @line = split ( /\t/ );
      $line[1] = &byteFormatter ( $line[1], 'MB' );
      $line[6] = " " if ( ! defined ( $line[6] ) );
      push ( @printable, join( "\t", $line[0], $line[1], $line[2], $line[3], $line[4], $line[5], $line[6] ) );
    }

    &setSimpleTXTOutput();
    &universalTextPrinter( "StgPoolName\tEstCapacity\tPctUtil\tPctMig\tHigh\tLow\tNextStgPool", @printable );

    return 0;

};
&defineAlias( 'dsk', 'show disks' );
&defineAlias( 'sh dsk', 'show disks' );

###############
# Show TIMIng ##########################################################################################################
###############
&msg( '0110D', 'SHow DISks' );
$Commands{&commandRegexp( "show", "timing" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "SHow TIMing Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    my @return;

    $LastCommandType = 'GENERAL';

    my @query = &runTabdelDsmadmc('q event * * begind=-1 begint=16:00 endd=today endt=now f=d '.$_[3]);
    return if ( $#query < 0 || $LastErrorcode );

    my @line;

    my $first_time;
    @line = split(/\t/, $query[0]);
    $first_time = &convert_date($line[3]);

    my $last_time;
    @line = split(/\t/, $query[$#query]);
    if ( $line[5] ne '' ) {
        $last_time = &convert_date($line[5]);
    }
    else {
        $last_time = &convert_date($line[3]);
    }

    &pbarInit( "PASS 1 |", $#query, "|");

    my $maxlength = 0;
    my $i = 0;
    foreach ( @query ) {
        my @line = split(/\t/);

        $line[7] = '?' if ( ! defined $line[7] );
        my $length = colorLength( ($i+1)." $line[1] $line[2] || $line[7]" );

        $maxlength = $length if ( $length > $maxlength );

        &pbarUpdate( $i );

        $i++;

    }

    my $size = $Settings{TERMINALCOLS} - $maxlength - 5; # 9

    my $quantum = ($size-1);
    $quantum = ($size-1)/($last_time-$first_time) if ( ($last_time-$first_time) > 0 );

    &pbarInit( "PASS 2 |", ($size-1), "|");

    # create an empty bar line
    my @emptybar;
    for ( my $i = 0; $i <= ($size-1); $i++ ) {
        $emptybar[$i] = ' ';
        &pbarUpdate( $i );
    }

    &pbarInit( "PASS 3 |", $#query, "|");

    $i = 0;
    for (@query) {
        my @line = split(/\t/);

        my @bar = @emptybar;

        &pbarUpdate( $i );

        $bar[int((&convert_date($line[3])-$first_time)*$quantum)] = 'S';

        if ( $line[6] =~ m/Future/i ) {
            &fill_bar(\@bar, int((&convert_date($line[3])-$first_time)*$quantum), ($size-1), 'f')
        }

        if ( $line[6] =~ m/Missed/i ) {
            &fill_bar(\@bar, int((&convert_date($line[3])-$first_time)*$quantum), ($size-1), 'M')
        }

        if ( $line[6] =~ m/(C|F)(ompleted|ailed)/i ) {
            &fill_bar(\@bar, int((&convert_date($line[3])-$first_time)*$quantum)+1, int((&convert_date($line[4])-$first_time)*$quantum)-1, 'w');
            &fill_bar(\@bar, int((&convert_date($line[4])-$first_time)*$quantum)+1, int((&convert_date($line[5])-$first_time)*$quantum)-1, 'r');

            $bar[int((&convert_date($line[4])-$first_time)*$quantum)] = 'A';
            $bar[int((&convert_date($line[5])-$first_time)*$quantum)] = "$1";
        }

        $line[7] = '?' if ( ! defined $line[7] );

        push( @return, join( "\t", ++$i, $line[1], $line[2], '|'.join('', @bar).'|', $line[7] ));

    }

    # "---\nS-ScheduleStart A-ActualStart r-Running C-Completed, F-Failed, M-Missed, f-furure\n";
    &setSimpleTXTOutput();
    &universalTextPrinter( "#\tScheduleName\tNodeName\tTiming\tRe", @return );

    return 0;

};

sub convert_date ($) {
  my $tmpdate = $_[0];

  return if ( ! defined $tmpdate || $tmpdate eq '' );

  $tmpdate =~ m/(\d\d)\/(\d\d)\/.*(\d\d) +(\d\d):(\d\d):(\d\d)/;
  return timelocal( $6, $5, $4, $2, $1-1, $3 );

};

sub fill_bar ( $$$$ ) {
    my $r_array   = $_[0];
    my $first_poz = $_[1];
    my $last_poz  = $_[2];
    my $value     = $_[3];

    for ( my $i = $first_poz; $i <= $last_poz; $i++ ) {
        @$r_array[$i] = $value;
    }
}

###############
# Show DRIVes ##########################################################################################################
###############
&msg( '0110D', 'SHow DRIves' );
$Commands{&commandRegexp( "show", "drives" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "SHow DRIves Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    $LastCommandType = 'DRIVE';

    my @query = &runTabdelDsmadmc( "select LIBRARY_NAME,DRIVE_NAME,'online='||ONLINE,ELEMENT,DRIVE_STATE,DRIVE_SERIAL,VOLUME_NAME from drives" );
    return if ( $#query < 0 || $LastErrorcode );

    &setSimpleTXTOutput();
    &universalTextPrinter( "#\tLibraryName\tDriveName\tOnline\tElement\tState\tSerial\tVolume", &addLineNumbers( @query ) );

    return 0;

};
&defineAlias( 's drive', 'show drives' );

########################################################################################################################

##############
# Show PAThs ###########################################################################################################
##############
&msg( '0110D', 'SHow PAThs' );
$Commands{&commandRegexp( "show", "paths" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "SHow PAThs Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    $LastCommandType = 'PATH';

    my @query = &runTabdelDsmadmc( "select SOURCE_NAME,DESTINATION_NAME,'srct='||SOURCE_TYPE,'destt='||DESTINATION_TYPE,LIBRARY_NAME,'device='||DEVICE,'online='||ONLINE from paths where LIBRARY_NAME is null" );
    return if ( $LastErrorcode );

    push ( @query, &runTabdelDsmadmc( "select SOURCE_NAME,DESTINATION_NAME,'srct='||SOURCE_TYPE,'destt='||DESTINATION_TYPE,'library='||LIBRARY_NAME,'device='||DEVICE,'online='||ONLINE from paths where LIBRARY_NAME is not null" ) );
    return if ( $#query < 0 || $LastErrorcode );

    &setSimpleTXTOutput();
    &universalTextPrinter( "#\tSourceName\tDestinationName\tSourceType\tDestinationType\tLibraryName\tDevice\tOnline", &addLineNumbers( @query ) );

    return 0;

};
&defineAlias( 's path', 'show path' );

########################################################################################################################

##########
# ONline ################################################################################################################
##########
&msg( '0110D', 'ONLine' );
$Commands{&commandRegexp( "online", "" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "ONLine Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    my $number = $2;

    if ( $number eq '' ) {
        &msg ( '0030E' );
        return 0;
    }

    $number--;

    if ( defined( $LastCommandType ) && $LastCommandType =~ m/DRIVE|PATH/ && $number <= $#LastResult ) {

        my @line = split ( /\t/, $LastResult[$number] );

        &setSimpleTXTOutput();
        &universalTextPrinter( "NOHEADER", &runDsmadmc( "update path  $line[1] $line[2] $line[3] $line[4] $line[5] online=yes") ) if ( $LastCommandType eq 'PATH' );
        &universalTextPrinter( "NOHEADER", &runDsmadmc( "update drive $line[1] $line[2] online=yes" ) )                           if ( $LastCommandType eq 'DRIVE' );

    }
    elsif ( $number > $#LastResult ) {

        &msg ( '0032E' ); # out of range

    }
    else {

        &msg ( '0031E', "Only 'SHow PAThs' OR 'SHow DRIves' allowed" );

    }

    return 0;

};
&defineAlias( 'on', 'online' );

########################################################################################################################

###########
# OFFline ##############################################################################################################
###########
&msg( '0110D', 'OFFline' );
$Commands{&commandRegexp( "offline", "" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "OFFline Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    my $number = $2;

    if ( $number eq '' ) {
        &msg ( '0030E' );
        return 0;
    }

    $number--;

    if ( defined( $LastCommandType ) && $LastCommandType =~ m/DRIVE|PATH/ && $number <= $#LastResult ) {

        my @line = split ( /\t/, $LastResult[$number] );

        &setSimpleTXTOutput();
        &universalTextPrinter( "NOHEADER", &runDsmadmc( "update path  $line[1] $line[2] $line[3] $line[4] $line[5] online=no" ) ) if ( $LastCommandType eq 'PATH' );
        &universalTextPrinter( "NOHEADER", &runDsmadmc( "update drive $line[1] $line[2] online=no" ) )                            if ( $LastCommandType eq 'DRIVE' );

    }
    elsif ( $number > $#LastResult ) {

        &msg ( '0032E' ); # out of range

    }
    else {

        &msg ( '0031E', "Only 'SHow PAThs' OR 'SHow DRIves' allowed" );

    }

    return 0;

};
&defineAlias( 'of', 'offline' );

########################################################################################################################

#################
# start dsmadmc ###########################################################################################################
#################
&msg( '0110D', 'STart DSMadmc' );
$Commands{&commandRegexp( "start", "dsmadmc" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "STart DSMadmc Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    $LastCommandType = 'GENERAL';

    if ( $3 =~ m/(nologin|no)/i ) {
        &startDsmadmc( );
    }
    else {
        &startDsmadmc( 'AUTOLOGIN' );
    }

    return 0;

};
&defineAlias( 'dsm', 'start dsmadmc' );

###############
# SHow EVEnts ##########################################################################################################
###############
&msg( '0110D', 'SHow EVEnts' );
$Commands{&commandRegexp( "show", "events" )} = sub {

    if ( $ParameterRegExpValues{HELP} ) {
        ###############################
        # Put your help message here! #
        ###############################
        print "--------\n";
        print "SHow EVEnts Help!\n";
        print "--------\n";

        $LastCommandType = "HELP";

        return 0;
    }

    $LastCommandType = 'EVENTS';

    my @query = &runTabdelDsmadmc('q event * * begind=-1 begint=07:00 endd=today endt=now f=d '.$3);
    return if ( $#query < 0 );

    @query = deleteColumn( 8, @query);

    &pbarInit( "PREPARATION |", $#query, "|");

    my $i = 0;
    my @printable;
    foreach ( @query ) {
        my @line = split(/\t/);


        if ( $line[3] =~ m/(\d\d\/\d\d\/\d\d\d\d\s*)/ ) {
            my $date = $1;
            $line[4] =~ s/$date//;
            $line[5] =~ s/$date//;
        }

        if ( ! defined ( $line[7] ) || $line[7] eq '' ) {

        }
        elsif ( $line[7] == 4 || $line[7] == 8 ) {
            $line[7] = colorString( $line[7], "BOLD YELLOW" );
        }
        elsif ( $line[7] == 12 ) {
            $line[7] = colorString( $line[7], "BOLD RED" );
        }

        push ( @printable, join( "\t", @line ) );

        &pbarUpdate( $i++ );

    }

    &setSimpleTXTOutput();
    &universalTextPrinter( "Domain\tScheduleName\tNodeName\tScheduledStart\tActStart{RIGHT}\tCompleted{RIGHT}\tStatus\tRC", @printable );

};

########################################################################################################################


1;